import { getData } from '~/server/plugins/getData'

export default defineEventHandler(async (event) => {
  try {
    // 获取查询参数
    const query = getQuery(event)
    const mainCategory = query.mainCategory as string // 必需参数，指定一级分类
    const dataSource = query.dataSource as string // 可选参数，指定数据源
    
    if (!mainCategory) {
      return {
        success: false,
        message: '一级分类参数不能为空',
        data: [],
        total: 0
      }
    }
    
    // 使用插件提供的数据
    const { getCurrentRequestData, getDataSourceData, getMainCategoryData } = getData()
    
    let categoryData: any = null
    
    if (dataSource) {
      // 如果指定了数据源，使用指定的数据源
      categoryData = getDataSourceData(dataSource)
    } else {
      // 否则使用当前域名的数据
      const currentData = getCurrentRequestData(event)
      if (currentData) {
        categoryData = currentData.data
      }
    }
    
    if (!categoryData) {
      return {
        success: false,
        message: '无法获取分类数据',
        data: [],
        total: 0
      }
    }
    
    // 检查一级分类是否存在
    if (!categoryData.mainCategories.includes(mainCategory)) {
      return {
        success: false,
        message: `一级分类 "${mainCategory}" 不存在`,
        data: [],
        total: 0,
        availableMainCategories: categoryData.mainCategories
      }
    }
    
    // 获取指定一级分类下的二级分类列表
    const subCategories = categoryData.subCategories[mainCategory] || []
    const categoryDataForMain = categoryData.categoryData[mainCategory] || {}
    
    // 构建二级分类列表，包含统计信息
    const subCategoryList = subCategories.map((subCategory: string) => {
      const apps = categoryDataForMain[subCategory] || []
      const appCount = Array.isArray(apps) ? apps.length : 0
      
      return {
        name: subCategory,
        displayName: subCategory, // 可以根据需要添加显示名称映射
        mainCategory: mainCategory,
        appCount,
        description: `包含 ${appCount} 个应用`,
        // 可选：返回前几个应用作为预览
        previewApps: apps.slice(0, 3).map((app: any) => ({
          name: app.name,
          icon: app.icon,
          developer: app.developer
        }))
      }
    })
    
    return {
      success: true,
      message: '获取二级分类列表成功',
      data: subCategoryList,
      total: subCategoryList.length,
      mainCategory,
      dataSource: dataSource || 'current',
      summary: {
        mainCategory,
        subCategoryCount: subCategoryList.length,
        totalAppCount: subCategoryList.reduce((total, sub) => total + sub.appCount, 0)
      }
    }
    
  } catch (error: any) {
    console.error('获取二级分类列表错误:', error)
    return {
      success: false,
      message: '获取二级分类列表过程中发生错误',
      data: [],
      total: 0,
      error: process.env.NODE_ENV === 'development' ? error?.message : undefined
    }
  }
}) 